package com.xiannimei.util.validate;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import javax.validation.constraints.Pattern;

import net.sf.json.JSONArray;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;

import com.xiannimei.Constants;

/**
 * 用于将后台验证规则应用于前台表单中
 * 
 * 2013-7-4 下午4:27:46
 * 
 * @author xinyuan.guo
 * 
 */
public class ValidateUtil {

	public static void getValidateJson(Model model, Class<?> c) {
		List<ValidateItem> items = new ArrayList<ValidateItem>();

		addItems(items, c);
		model.addAttribute("vitems", JSONArray.fromObject(items).toString().replaceAll("\\\\\\\\", "\\\\\\\\\\\\\\\\"));
	}

	private static void addItems(List<ValidateItem> items, Class<?> c) {
		Field[] declaredFields = c.getDeclaredFields();
		for (Field field : declaredFields) {
			field.setAccessible(true);
			if (field.isAnnotationPresent(Pattern.class)) {
				Pattern annotation = field.getAnnotation(Pattern.class);
				ValidateItem item = new ValidateItem();
				item.name = field.getName();
				item.reg = annotation.regexp();
				item.warn = getBundelKey(annotation.message());
				items.add(item);
			}
		}
		Class<?> superclass = c.getSuperclass();
		if (superclass != null) {
			addItems(items, superclass);
		}
	}
	
	private static String getBundelKey (String oKey) {
		String key = oKey.substring(1, oKey.length() - 1);
		return ResourceBundle.getBundle(Constants.MSG_BUNDEL_PATH, LocaleContextHolder.getLocale()).getString(key);
	}
	
	public static List<String> getErrorFileds(Errors errors) {
		List<String> list = new ArrayList<String>();
		for (FieldError error : errors.getFieldErrors()) {
			list.add(error.getField());
		}
		return list;
	}
}
